<?php

require_once('jhtraq.php');
class JhtraqModelVersions extends JhtraqModelJhtraq
{
	
	function get($id, $method = 'loadObject')
	{
		$this->db->setQuery("Select * from #__jhtraq_versions where id='".(int)$id."'");
		return $this->db->$method();
	}
	
	function getList()
	{
		$this->db->setQuery("Select id,version as name from #__jhtraq_versions order by name asc");
		$res = $this->db->loadObjectList();
		$return=array();
		foreach($res as $row)
			$return[$row->id] = $row->name;
		
		return $return;
	}
	
	function getPaged()
	{
		$mainframe =& JFactory::getApplication();
		$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		jimport('joomla.html.pagination');
		$search = JRequest::getVar('search');
		$project = (int)JRequest::getVar('project');
		
		$query = "Select SQL_CALC_FOUND_ROWS * from #__jhtraq_versions";
		if($search != '')
		$query .= "Where version like'%$search%' ";
		if($project > 0 && $search != '')
		{
			$query .= " AND project_id='$project'";
		}elseif($project > 0 && $search == '')
		{
			$query .= " Where project_id='$project'";
		}
		
		$query .= ' ORDER BY version ASC';
		
		$this->db->setQuery($query,$limitstart, $limit );
		$r =&$this->db->loadAssocList();
		//	print_r($this->db);
		
		$this->db->setQuery('SELECT FOUND_ROWS();');
		$this->_pagination = new JPagination( $this->db->loadResult(), $limitstart, $limit );
		
		return $r;
	}
	
	function remove($ids)
	{
		if(!is_array($ids))
			$ids = array();
		
		$this->db->setQuery("Delete from #__jhtraq_versions where id in(".implode(",",$ids) . ")");
		return $this->db->query();
	}
	
	function save($post)
	{
		$id = (int)$post['id'];
		$name = $this->db->getEscaped($post['version']);
		$project_id = (int)$post['project_id'];
		
		$q = "Set version='$name',project_id='$project_id'";
		if($id > 0)
		{
			//update
			$query = "Update #__jhtraq_versions " . $q . " where id='$id'";
		}else{
			//insert
			$query = "Insert into #__jhtraq_versions " . $q;
		}
		$this->db->setQuery($query);
		return $this->db->query();
	}
}